package parallels.servertech.server.nio;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.util.logging.Logger;

public class NonBlockingChannelInputStream extends InputStream {
	private static final Logger log = Logger.getLogger("input");
	
	private static final int BUF_SIZE = 4096;
	
	private final ByteChannel channel;
	private ByteBuffer buffer;
	
	public NonBlockingChannelInputStream(ByteChannel channel) {
		this.channel = channel;
	}
	
	@Override
	public int read() throws IOException {
		if (buffer != null) {
			if (buffer.hasRemaining()) {
				return buffer.get();
			} else {
				buffer.clear();
				return fillAndRead();
			}
		} else {
			buffer = ByteBuffer.allocate(BUF_SIZE);
			return fillAndRead();
		}
	}
	
	private int fillAndRead() throws IOException {
		int bytes = channel.read(buffer);
		log.info(bytes + " bytes read from channel");
		buffer.flip();
		return buffer.hasRemaining() ? buffer.get() : -1;
	}
}
